package com.laoniu.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtUtils {

    private static final String JWT_KEY= "laoniu";
    private static final Long JWT_TTL = 1000 * 60 * 60 *24 * 7L;

    public static String createJwt(String subject, Long userId){
        JwtBuilder builder = getJwtBuilder(subject, StringUtils.genUUID(), userId);// 设置过期时间
        return builder.compact();
    }
    private static JwtBuilder getJwtBuilder(String subject, String uuid, Long userid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        long expMillis = nowMillis + JWT_TTL;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("laoniu")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate)
                .claim("userId", userid)
                ;
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     * 解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
//        String liuxuli = createJwt("liuxuli", 12222L);
//        System.out.println(liuxuli);
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjY2RhOWQ4NTZmZDA0NzQzYWViMmQ0ODIyYWJjODc4YiIsInN1YiI6ImxpdXh1bGkiLCJpc3MiOiJsYW9uaXUiLCJpYXQiOjE3MDI1MTk2NDYsImV4cCI6MTcwMzEyNDQ0NiwidXNlcklkIjoxMjIyMn0.JEAladMhKxQ9O3AbObU99hWHBW9Ejgf5nebaxe9YHNA";
        try {
            Claims claims = parseJWT(jwt);
            System.out.println(claims.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
